import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // 设置路由表
  // 一级路由
  {
    path: '/home',
    name: 'home',
    meta: { title: '饿了么' },
    component: () => import('../views/home.vue'),
    children: [
      {
        path: '/home/index',
        name: 'index',
        meta: { title: '首页' },
        component: () => import('../views/home1/Index.vue'),
      },
      {
        path: '/home/bao',
        name: 'bao',
        meta: { title: '爆爆团' },
        component: () => import('../views/home1/bao.vue'),
      },
      {
        path: '/home/dingdan',
        name: 'dingdan',
        meta: { title: '订单' },
        component: () => import('../views/home1/dingdan.vue'),
        // 设置路由独享的路由守卫函数
        // beforeEach:(to,from,next)=>{

        // }
      },
      {
        path: '/home/mine',
        name: 'mine',
        meta: { title: '我的' },
        component: () => import('../views/home1/mine.vue'),
      },
      {
        path: '/home',
        redirect: '/home/index'
      },
      {
        path: '*',
        component: () => import('../views/404.vue'),
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    meta: { title: '登录' },
    component: () => import('../views/login.vue')
  },
  {
    path: '/zhuce',
    name: 'zhuce',
    meta: { title: '注册' },
    component: () => import('../views/zhuce.vue')
  },
  // 设置以及路由重定向
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '*',
    component: () => import('../views/404.vue'),
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 在实例化路由对象后面设置前置路由守卫函数
router.beforeEach((to, from, next) => {
  document.title = to.meta.title;
  // 设置访问订单页面和我的页面时需要判断是否登录
  var token = localStorage.getItem('token')
  if (to.path == '/home/dingdan' || to.path == '/home/mine') {
    if (token) {
      next();//token存在表示已经登录，允许跳转
    } else {
      next('/login')
    }
  } else {
    next()
  }

})
export default router
